DOM events as a Svelte store

Posted on 2023-02-12 by

henrikvilhelmberglund

Here we are going to try to convert the following example into a Svelte store:

Mouse position: 0, 0
<script>
	import { onMount } from "svelte";
	let x = 0;
	let y = 0;
	onMount(() => {
		function move(event) {
			x = event.clientX;
			y = event.clientY;
		}
		document.body.addEventListener("mousemove", move);
		return () => {
			document.body.removeEventListener("mousemove", move);
		};
	});
</script>

Mouse position: {x}, {y}

<style>
</style>

Here it is as a Svelte store:

Mouse position: 0, 0
Child mouse position: 0, 0
<script>
	import mousePosition from "./mousePosition";
	import Child from "./Child.svelte";
</script>

Mouse position: {$mousePosition.x}, {$mousePosition.y}

<div>
	<Child />
</div>

This page has no real explanation because this page basically broke the whole site until I found out you could have on onMount after the export in mousePosition.js (no idea if this is how it should work), but basically this is a readable store that handles DOM events as the store values.

May revisit later!